/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ergasia3h;


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.mapviewer.Waypoint;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

/**
 *
 * @author ndrosos
 */
public class Utils {
    public static ImageIcon scale(Image src, double size, ImageObserver o) {
        double scale = size/src.getWidth(o);
        int w = (int)(scale*src.getWidth(o));
        int h = (int)(scale*src.getHeight(o));
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage dst = new BufferedImage(w, h, type);
        Graphics2D g2 = dst.createGraphics();
        g2.drawImage(src, 0, 0, w, h, o);
        g2.dispose();
        return new ImageIcon(dst);
    }

    public static GeoPosition getGeoposition(String name){
        URL url;
        if (name.contains(" "))
            name = name.replace(" ", "%20");
        try {
            url = new URL("http://ws.geonames.org/wikipediaSearch?q=" + name);
            XPath xpath = XPathFactory.newInstance().newXPath();
            Reader reader = new InputStreamReader(url.openStream(),"UTF8");
            InputSource is = new InputSource(reader);
            is.setEncoding("UTF8");

            Node node = (Node)xpath.evaluate("//entry", is, XPathConstants.NODE);

            Waypoint waypoint = new Waypoint();
            Double lat = (Double) xpath.evaluate("lat/text()",
                node, XPathConstants.NUMBER);
            Double lon = (Double) xpath.evaluate("lng/text()",
                node, XPathConstants.NUMBER);
            waypoint = new Waypoint(lat, lon);
            return waypoint.getPosition();
         } catch (Exception ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.WARNING, null, ex);
            return null;
        }
    }
}

